package api

import (
	"context"
	"fmt"
	"github.com/jinzhu/copier"
	"github.com/labstack/echo/v4"
	"longmen/server/pkg/common/api_models"
	string2 "longmen/server/pkg/common/helper/string"
	"longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/grpc_client"
	"longmen/server/pkg/protobuf"
)

/**
 * @author Aaron
 * @description 用户获取任务列表
 * @createTime 9:26 2022/5/17
 **/
// @Summary 用户获取任务列表
// @Description 用户获取任务列表
// @Accept  json
// @Produce  json
// @Tags Task
// @Param   sendBody body api_models.GetTaskListReq true "body"
// @Success 200 {object} api_models.GetTaskListResp "result"
// @Router /api/task/getTaskList [POST]
func (base *Controller) GetTaskList(c echo.Context) error {
	req := &api_models.GetTaskListReq{}
	if err := util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	o, err := grpc_client.GrpcTaskServer.GetTaskList(context.Background(), &protobuf.GetTaskListReq{
		Page: uint32(string2.GetDefaultNum(req.Page, 1)),
		Size: uint32(string2.GetDefaultNum(req.Size, 20)),
		Uid:  uint64(c.Get("uid").(int)),
	})
	if err != nil {
		return util.BuildFail(c, 1, "", err)
	}

	resp := make([]*api_models.GetTaskListResp, 0)
	for _, task := range o.GetGetTaskListResp() {
		des := &api_models.GetTaskListResp{}
		err = copier.Copy(des, task)
		if err != nil {
			return fmt.Errorf("%s%s", util.Convert2(), err.Error())
		}
		des.BeginTime = timehelper.Stamp2Time(task.GetBeginTime().Seconds)
		des.EndTime = timehelper.Stamp2Time(task.GetEndTime().Seconds)
		if len(task.Gift) == 0 {
			des.Gift = []*api_models.Gift{}
		}
		resp = append(resp, des)
	}
	if len(o.GetGetTaskListResp()) == 0 {
		return util.BuildSuccess(c, []interface{}{}, "")
	}
	return util.BuildSuccess(c, resp, "") /**/
}

/**
 * @author Aaron
 * @description 任务领取记录
 * @createTime 10:09 2022/5/24
 **/
//@Summary 任务领取记录 需登入
//@Description 任务领取记录 需登入
//@Accept  json
//@Produce  json
//@Tags Task
//@Param   sendBody body api_models.GetRecordReq true "body"
//@Success 200 {object} protobuf.GetRecordResp "result"
//@Router /api/task/getRecord [POST]
func (base *Controller) GetRecord(c echo.Context) error {
	req := &api_models.GetRecordReq{}
	if err := util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	resp, err := grpc_client.GrpcTaskServer.GetRecord(context.Background(), &protobuf.UidReq{
		Uid:  uint64(c.Get("uid").(int)),
		Page: uint32(string2.GetDefaultNum(req.Page, 1)),
		Size: uint32(string2.GetDefaultNum(req.Size, 20)),
	})
	if err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	if len(resp.GetGetRecordResp()) == 0 {
		return util.BuildSuccess(c, []interface{}{}, "")
	}
	for _, r := range resp.GetGetRecordResp() {
		if len(r.Gift) == 0 {
			r.Gift = []*protobuf.Gift{}
		}
	}
	return util.BuildSuccess(c, resp.GetGetRecordResp(), "")
}
